#!/usr/bin/env python2

import os
import re


def rmlast(flist):
    """
    Given a package filename list, this function removes from the list only the
    latest version of the package, examples:
    >>> rmlast(['b-1.0', 'd-2.0', 'a-10.1', 'b-2.0', 'b-3.0', 'c-1.0', 'a-2.0'])
    ['a-2.0', 'b-1.0', 'b-2.0']
    >>> rmlast([])
    []
    >>> rmlast(['a-1.2.tar.gz'])
    []
    >>> rmlast(['j-2', 'j-1', 'gstreamer0.10-base-plugins-0.10.30-1-i686.pkg.tar.xz', 'gstreamer0.10-python-0.10.18-3-i686.pkg.tar.xz'])
    ['j-1']
    >>> rmlast(['b-1', 'b-2', 'a-1'])
    ['b-1']
    """
    flist.sort()
    i, rlist, re_pkname, re_vnum = 0, [], re.compile(r'([a-z][\w\.\+]*-)+'), re.compile(r'\d+')
    while i < len(flist):
        # take this pkg name and version numbers
        pkg = re.match(re_pkname, flist[i]).group()
        vlist = [([int(x) for x in re.findall(re_vnum, flist[i])], flist[i])]
        # search same pkgs and append the version numbers
        i += 1
        if i < len(flist):
            next_pkg = re.match(re_pkname, flist[i]).group()
            while i < len(flist) and pkg == next_pkg:
                vlist.append(([int(x) for x in re.findall(re_vnum, flist[i])], flist[i]))
                i += 1
                if i < len(flist): # take next only if not already in the last pos
                    next_pkg = re.match(re_pkname, flist[i]).group()
        # sort the version number list
        vlist.sort()
        for _, fname in vlist[:-1]:
            rlist.append(fname) # append all but the last item to the result
    return rlist


if __name__ == '__main__':
    pacdir = '/var/cache/pacman/pkg'
    print '\n'.join([os.path.join(pacdir, f) for f in rmlast(os.listdir(pacdir))])
